package com.skyline.spot.controller;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import net.imagine.core.ResultState;
import net.imagine.provider.skyline.ImageCropResult;
import net.imagine.provider.skyline.ImageCutter;
import net.imagine.provider.skyline.SkylineImageCropTask;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.RedirectView;

import com.skyline.base.controller.BaseController;
import com.skyline.base.exception.NotLoginException;
import com.skyline.base.exception.OperateFailedException;
import com.skyline.base.type.Activity;
import com.skyline.base.type.Authority;
import com.skyline.base.type.RatyObjType;
import com.skyline.base.type.SpotRefrenceType;
import com.skyline.base.type.SpotType;
import com.skyline.common.bean.Page;
import com.skyline.common.util.Constant;
import com.skyline.common.util.ViewPaths;
import com.skyline.common.util.WebHelper;
import com.skyline.spot.model.Spot;
import com.skyline.spot.model.SpotCharacteristic;
import com.skyline.spot.model.SpotRefrence;
import com.skyline.spot.service.RatyService;
import com.skyline.spot.service.SpotCharacteristicService;
import com.skyline.spot.service.SpotRefrenceService;
import com.skyline.spot.service.SpotService;
import com.skyline.user.model.Fan;
import com.skyline.user.model.User;
import com.skyline.user.service.AttentionService;
import com.skyline.wo.model.Album;
import com.skyline.wo.model.Photo;
import com.skyline.wo.service.AlbumService;

@RequestMapping("/spot")
@Controller
public class SpotController extends BaseController {
//	private static final Log LOGGER = LogFactory.getLog(SpotController.class);
	@Autowired
	private SpotService spotService;
	@Autowired
	private SpotRefrenceService spotRefrenceService;
	@Autowired
	private AttentionService attentionService;
//	@Autowired
//	private ArticleService articleService;
	@Autowired
	private RatyService ratyService;
	@Autowired
	private SpotCharacteristicService spotCharacteristicService;
	@Autowired
	private AlbumService albumService;

	@Autowired
	private ImageCutter crop;
	@Value("${imagine.protraitSize}")
	private int portraitSize;
	@Value("${imagine.localStorePath}")
	private String basePath;
	
	private @Value("${spot.test.pagesize}")
	int spotPageSize;

//	private @Value("${refrence.listrefrence.pagesize}")
//	int listRefrencePageSize;

//	private @Value("${view.spot.discovery}")
//	String discoveryView;
//
//	private @Value("${view.user.login}")
//	String loginView;
//	private @Value("${view.spot.view}")
//	String spotView;
//	private @Value("${view.spot.edit}")
//	String editView;
//	private @Value("${view.spot.editPortrait}")
//	String editPortraitView;
//	private @Value("${view.spot.uploadPhoto}")
//	String uploadPhotoView;
//
//	private @Value("${view.spot.notfound}")
//	String notFoundView;
//
//	private @Value("${view.spot.list}")
//	String spotListView;
//	private @Value("${view.spot.refrence.list}")
//	String spotRefrenceListView;
//	private @Value("${view.spot.refrence.detail}")
//	String spotRefrenceDetailView;
//	private @Value("${view.spot.refrence.add}")
//	String spotRefrenceAddView;

	// test

//	private @Value("${view.spot.map}")
//	String mapView;
//	private @Value("${view.spot.note}")
//	String noteView;

	@RequestMapping(value = "/isexit", method = RequestMethod.POST)
	public @ResponseBody
	Boolean isExitSpotByName(@RequestParam("name") String spotName) {
		return spotService.isExist(spotName);
	}

	/**
	 * 添加景点用请求函数
	 * 
	 * @returnzise
	 */
	@RequestMapping(value = "/discovery", method = RequestMethod.GET)
	public ModelAndView discoverySpotrequest() {
		User user = (User) WebHelper.getSessionAttribute(null, Constant.SESSION_USER);
		ModelAndView v = new ModelAndView();
		if (user == null) {
			v.setViewName(ViewPaths.USER_LOGIN);
			return v;
		}
		v.setViewName(ViewPaths.SPOT_DISCOVERY);
		return v;
	}

	/**
	 * 添加景点用请求函数
	 * 
	 * @return
	 */
	@RequestMapping(value = "/{spotId}/editPortrait", method = RequestMethod.GET)
	public ModelAndView uploadPortraitSpotrequest(@PathVariable("spotId") Long spotId) {
		User user = (User) WebHelper.getSessionAttribute(null, Constant.SESSION_USER);
		ModelAndView v = new ModelAndView();
		if (user == null) {
			v.setViewName(ViewPaths.USER_LOGIN);
			return v;
		}
		Spot spot = spotService.getSpot(spotId);
		if (spot.getAdministratorId().equals(user.getId())) {
			Album portraitAlbum = albumService.getUserPortraitAlbum(spotId);
			Photo portraitPhoto = albumService.getCurrentPortraitPhotoFromAlbum(portraitAlbum);
			v.addObject("portraitAlbumId", portraitAlbum.getId());
			v.addObject("portrait", portraitPhoto);
			v.addObject("spotInfo", spot);
			v.setViewName(ViewPaths.SPOT_EDITPORTRAIT);
		}
		// 没权限
		else {
			v.setViewName(ViewPaths.SPOT_NOTFOUND);
		}
		return v;
	}

	@RequestMapping(value = "/{spotId}/editPortrait", method = RequestMethod.POST)
	public ModelAndView uploadPortraitSpotrequestOk(Long spotId, Integer x, Integer y,
			Integer size, String submitToken) {
		User user = (User) WebHelper.getSessionAttribute(null, Constant.SESSION_USER);
		if (user == null) {
			throw new NotLoginException("上传头像必须登录");
		}

		String errMsg = this.validateForm("portraitUploadForm", submitToken);
		if (errMsg != null) {
			return processValidationErrors("errMsg", errMsg, photoUploadRequest());
		}
		Photo portrait = albumService.getUserCurrentPortraitPhoto(spotId);
		if (portrait == null) {
			throw new OperateFailedException("不存在当前图片，无法剪切");
		}
		long albumId = portrait.getAlbumId();

		String smallFile = portrait.getSmallFile();
		String ext = portrait.getExt();
		String remoteFileKey = smallFile + '.' + ext;

		SkylineImageCropTask cropTask = new SkylineImageCropTask(remoteFileKey, portraitSize);
		cropTask.setAlbumId(albumId);
		cropTask.setUserId(spotId);
		cropTask.setOffsetX(x);
		cropTask.setOffsetY(y);
		cropTask.setCropSize(size);
		ImageCropResult cropResult;
		try {
			cropResult = crop.processImage(basePath, cropTask);
		} catch (IOException e) {
			throw new OperateFailedException("无法剪切图片");
		}
		if (cropResult == null || cropResult.getResultState() != ResultState.SUCCESS) {
			throw new OperateFailedException("无法剪切图片，原因："
					+ (cropResult == null ? null : cropResult.getResultState()));
		}
		String portraitFile = cropResult.getFileKey();

		spotService.updateSpotPortrait(spotId, portraitFile);
		// personalInfoService.changeUserPortrait(ownerId, portraitFile);
		// spot.setPortrait(portraitFile);
		WebHelper.setSessionAttribute(null, Constant.SESSION_USER, user);

		String url = buildRecirectPath("/spot/" + spotId);
		ModelAndView view = new ModelAndView(new RedirectView(url));
		return view;
	}

	/**
	 * 添加景点递交请求函数
	 */
	@RequestMapping(value = "/discovery", method = RequestMethod.POST)
	public ModelAndView addSpotRequest(Spot spot) {
		ModelAndView v = new ModelAndView();
		/**
		 * Map<String, Object> data = new HashMap<String, Object>(5, 1F);
		 * data.put("name", spot.getName()); data.put("detailAddress",
		 * spot.getDetailAddress()); data.put("introduction",
		 * spot.getIntroduction()); String errMsg =
		 * validateForm("discoverySpotForm", data); if(errMsg != null) {
		 * ModelAndView errMav = this.processValidationErrors("errMsg", errMsg,
		 * discoverySpotrequest()); return errMav; }
		 */
		try {
			User user = (User) WebHelper.getSessionAttribute(null, Constant.SESSION_USER);
			if (user == null) {
				v.setViewName(ViewPaths.USER_LOGIN);
				return v;
			}
			if (spotService.isExist(spot.getName())) {
				// 已经存在
				v.setViewName("redirect:discovery.html");
				return v;
			}
			long spotId = spotService.discoverySpot(user, spot);
			if (spotId == 0) {
				// 添加spot出错
				v.setViewName("redirect:discovery.html");
				return v;
			}
			// FIXME 为spot增加一个默认相册，用于保存头像和一些照片
//			Album album = albumService.getUserPortraitAlbum(spotId);

			v.setViewName("redirect:" + spotId + "/editPortrait.html");

			return v;
		} catch (Exception e) {
			e.printStackTrace();
			v.setViewName(ViewPaths.USER_LOGIN);
			return v;
		}
		// todo 增加相册
	}

	@RequestMapping(value = "/photoupload", method = RequestMethod.GET)
	public ModelAndView photoUploadRequest() {
		User user = (User) WebHelper.getSessionAttribute(null, Constant.SESSION_USER);
		if (user == null) {
			throw new NotLoginException("上传头像必须登录");
		}

		long ownerId = user.getId();
		Album portraitAlbum = albumService.getUserPortraitAlbum(ownerId);
		Photo portraitPhoto = albumService.getCurrentPortraitPhotoFromAlbum(portraitAlbum);

		ModelAndView view = new ModelAndView();
		view.addObject("portraitAlbum", portraitAlbum);
		view.addObject("portrait", portraitPhoto);
		// view.setViewName(photoUploadView);
		return view;
	}

	/**
	 * 景点主页请求显示函数
	 * 
	 * @param spotId
	 * @return
	 */
	@RequestMapping(value = "/{spotId}", method = RequestMethod.GET)
	public ModelAndView viewSpotRequest(@PathVariable("spotId") Long spotId) {
		ModelAndView v = new ModelAndView(ViewPaths.USER_LOGIN);
		Page page = new Page();
		page.setSize(spotPageSize);
		Integer authority = Authority.PUBLIC;
		User user = (User) WebHelper.getSessionAttribute(null, Constant.SESSION_USER);
		Spot spotInfo = spotService.view(spotId);
		if (spotInfo == null) {
			v.setViewName(ViewPaths.SPOT_NOTFOUND);
			return v;

		}
		spotService.addVisitNum(spotId);

		if (user != null) {
			if (attentionService.isFan(spotId, user.getId())) {
				authority = Authority.ONLY_TO_FANS;
			}

			if (user.getId().equals(spotInfo.getAdministratorId())) {
				authority = Authority.PRIVATE;
			}
		}
		List<SpotCharacteristic> scList = spotCharacteristicService.queryCharacteristicBySpotId(
				spotId, page, Activity.NORMAL);

		/**
		 * spot 的默认相册即才有头像相册的形式
		 */
		Album defaultAlbum = albumService.getUserPortraitAlbum(spotId);
		List<SpotRefrence> refList = spotRefrenceService.getRefrencesBySpotIdAndType(spotId,
				SpotRefrenceType.ALBUM, page);

		List<Fan> fanList = attentionService.queryFans(spotId, page);
		int fanCounts = attentionService.countFans(spotId);
		v.setViewName(ViewPaths.SPOT_VIEW);
		v.addObject("spotInfo", spotInfo);
		v.addObject("fansNum", fanCounts);
		if (scList.isEmpty()) {
			v.addObject("spotCharaList", null);
		} else {
			v.addObject("spotCharaList", scList);
		}
		v.addObject("defaultAlbum", defaultAlbum);
		v.addObject("refList", refList);
		v.addObject("fanList", fanList);
		v.addObject("authority", authority);
		// v.addObject("essaysList", spotRefrenceListOfEssays);
		return v;

	}

	/**
	 * 根据国家分类显示请求函数
	 * 
	 * @param country
	 * @param province
	 * @param page
	 * @return
	 */
	@RequestMapping(value = "/list", method = RequestMethod.GET)
	public ModelAndView viewSpotListRequest(Page page) {
		ModelAndView v = new ModelAndView(ViewPaths.USER_LOGIN);
		page.setSize(spotPageSize);
		try {
			List<Spot> spotList = spotService.findAll(SpotType.VIEWPOINT, page, Activity.NORMAL);
			v.setViewName(ViewPaths.SPOT_LIST);
			v.addObject("spotList", spotList);
			v.addObject("page", page);
			v.addObject("scope", 0);
			return v;
		} catch (Exception e) {
			return v;
		}

	}

	/**
	 * 根据国家分类显示请求函数
	 * 
	 * @param country
	 * @param province
	 * @param page
	 * @return
	 */
	@RequestMapping(value = "/country/{siteId}/list", method = RequestMethod.GET)
	public ModelAndView viewSpotListBycountryRequest(@PathVariable("siteId") String siteId,
			Page page) {
		ModelAndView v = new ModelAndView(ViewPaths.USER_LOGIN);
		String countryId = siteId.substring(0, 3);
		page.setSize(spotPageSize);
		try {
			List<Spot> spotList = spotService.findByCountry(countryId, SpotType.VIEWPOINT, page,
					Activity.NORMAL);
			v.setViewName(ViewPaths.SPOT_LIST);
			v.addObject("spotList", spotList);
			v.addObject("page", page);
			v.addObject("scope", 1);
			return v;
		} catch (Exception e) {
			return v;
		}

	}

	/**
	 * 根据省份分类显示请求函数
	 * 
	 * @param country
	 * @param province
	 * @param page
	 * @return
	 */
	@RequestMapping(value = "/province/{siteId}/list", method = RequestMethod.GET)
	public ModelAndView viewSpotListByProvinceRequest(@PathVariable("siteId") String siteId,
			Page page) {
		ModelAndView v = new ModelAndView(ViewPaths.USER_LOGIN);
		String provinceId = siteId.substring(0, 5);
		page.setSize(spotPageSize);
		try {
			List<Spot> spotList = spotService.findByProvince(provinceId, SpotType.VIEWPOINT, page,
					Activity.NORMAL);
			v.setViewName(ViewPaths.SPOT_LIST);
			v.addObject("spotList", spotList);
			v.addObject("page", page);
			v.addObject("scope", 2);
			return v;
		} catch (Exception e) {
			return v;
		}

	}

	/**
	 * 根据城市分类显示请求函数
	 * 
	 * @param country
	 * @param province
	 * @param city
	 * @param page
	 * @return
	 */
	@RequestMapping(value = "/city/{siteId}/list", method = RequestMethod.GET)
	public ModelAndView viewSpotListByCityRequest(@PathVariable("siteId") String siteId, Page page) {
		ModelAndView v = new ModelAndView(ViewPaths.USER_LOGIN);
		String cityId = siteId.substring(0, 7);
		page.setSize(spotPageSize);
		try {
			List<Spot> spotList = spotService.findByCity(cityId, SpotType.VIEWPOINT, page,
					Activity.NORMAL);
			v.setViewName(ViewPaths.SPOT_LIST);
			v.addObject("spotList", spotList);
			v.addObject("page", page);
			v.addObject("scope", 3);
			return v;
		} catch (Exception e) {
			return v;
		}

	}

	/**
	 * 重新编辑景点请求函数
	 * 
	 * @param spotId
	 * @return
	 */
	@RequestMapping(value = "/{spotId}/edit", method = RequestMethod.GET)
	public ModelAndView modifySpotRequest(@PathVariable("spotId") Long spotId) {
		User user = (User) WebHelper.getSessionAttribute(null, Constant.SESSION_USER);
		ModelAndView v = new ModelAndView(ViewPaths.USER_LOGIN);

		Spot spot = spotService.view(spotId);
		if (spot == null)
			return null;
		if(spot.getAdministratorId().equals(user.getId()))
		{
		v.setViewName(ViewPaths.SPOT_EDIT);
		v.addObject("spotInfo", spot);
		}
		return v;
	}

	@RequestMapping(value = "/{spotId}/editbasic", method = RequestMethod.POST)
	public ModelAndView submitModifySpotBasicRequest(@PathVariable("spotId") Long spotId, Spot spot) {
		ModelAndView v = new ModelAndView(ViewPaths.USER_LOGIN);
		User user = (User) WebHelper.getSessionAttribute(null, Constant.SESSION_USER);
		if (user == null)
			return v;
		if (user.getId().equals(spot.getAdministratorId())) {
			spotService.updateSpotInfo(spot);
			spot = spotService.view(spotId);
			if (spot == null)
				return null;
			v.setViewName(ViewPaths.SPOT_EDIT);
			v.addObject("spotInfo", spot);
			return v;
		} else {
			return v;
		}
	}

	@RequestMapping(value = "/{spotId}/editintro", method = RequestMethod.POST)
	public ModelAndView submitModifySpotIntroRequest(@PathVariable("spotId") Long spotId, Spot spot) {
		ModelAndView v = new ModelAndView(ViewPaths.USER_LOGIN);
		User user = (User) WebHelper.getSessionAttribute(null, Constant.SESSION_USER);
		if (user == null)
			return v;
		if (user.getId().equals(spot.getAdministratorId())) {
			spotService.updateSpotIntroduction(spotId, spot.getIntroduction());
			spot = spotService.view(spotId);
			if (spot == null)
				return null;
			v.setViewName(ViewPaths.SPOT_EDIT);
			v.addObject("spotInfo", spot);
			return v;
		}
		return v;
	}

	/**
	 * 打开批量上传图片到相册的页面
	 * 
	 * @param albumId
	 *            相册ID
	 * @param request
	 * */
	@RequestMapping(value = "/{spotId}/upload/{albumId}", method = RequestMethod.GET)
	public ModelAndView btachUpload(@PathVariable("spotId") Long spotId,
			@PathVariable("albumId") Long albumId) {
		User user = (User) WebHelper.getSessionAttribute(null, Constant.SESSION_USER);
		if (user == null) {
			throw new NotLoginException("上传照片必须登录");
		}
		Album album = albumService.getAlbumForChange(albumId, spotId);
		ModelAndView mav = new ModelAndView(ViewPaths.SPOT_UPLOADPHOTO);
		mav.addObject("album", album);
		// WebHelper.saveToken(request);
		return mav;
	}

	public ModelAndView verifySpot(@PathVariable String name) {
		try {
			WebHelper.initResponse(null).getWriter()
					.write(String.valueOf(spotService.isExist(name)));
		} catch (IOException e) {
			// TODO:记录日志

		}
		return null;
	}

	/**
	 * @param spotId
	 * @param star
	 * @param httpServletRequest
	 * @return
	 */
	@RequestMapping(value = "/vote", method = RequestMethod.POST)
	public @ResponseBody
	Map<String, Object> ajaxvote(@RequestParam("objId") Long objId,
			@RequestParam("star") Integer star) {
		Map<String, Object> map = new HashMap<String, Object>();
		try {

			User user = (User) WebHelper.getSessionAttribute(null, Constant.SESSION_USER);
			if (user == null) {
				map.put("loginStatus", false);
				return map;
			}
			map.put("loginStatus", true);
			if (ratyService.isRaty(objId, user.getId())) {
				Spot spot = spotService.view(objId);

				map.put("SpotStar", spot.getStar());
				map.put("VoteNum", spot.getVotes());
				map.put("Raty_Tag", true);
				return map;
			}
			Spot spot = (Spot) ratyService.ratyStar(objId, RatyObjType.SPOT, user.getId(), star);
			map.put("Star", spot.getStar());
			map.put("VoteNum", spot.getVotes());
			return map;

		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}

	}

	/***************************************************************
	 * ajax request
	 * 
	 * @return
	 ***************************************************************/
	@RequestMapping(value = "{spotId}/map", method = RequestMethod.GET)
	public ModelAndView viewMapRequest(@PathVariable("spotId") Long spotId) {
		ModelAndView v = new ModelAndView(ViewPaths.SPOT_MAP);
		Spot spotInfo = spotService.view(spotId);
		v.addObject("spotInfo", spotInfo);
		return v;
	}

	@RequestMapping(value = "/note", method = RequestMethod.GET)
	public ModelAndView viewNoteRequest() {
		ModelAndView v = new ModelAndView(ViewPaths.SPOT_NOTE);
		return v;
	}

	/**
	 * Demo refrence
	 */

}
